﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Dukou.Authentication.Dao;
using Dukou.Authentication.Domain;
using Spring.Transaction.Interceptor;
using System.Threading;
using System.Security.Cryptography;

namespace Dukou.Authentication.BizService.Impl
{
    [Serializable]
    public class AuthenticationBizService : IAuthenticationBizService
    {
        private readonly static string __TIKET_KEY = "DUKOU_AUTHENTICATION_TIKET";

        /// <summary>
        /// 
        /// </summary>
        public ILogonInfoDao LogonInfoDao { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public IUserDao UserDao { get; set; }

        public ISecretKeyDao SecretKeyDao { get; set; }

        public string TiketKey
        {
            get
            {
                return __TIKET_KEY;
            }
        }

        public User CurrentUser 
        {
            get 
            {
                string tiket = Thread.GetData(Thread.GetNamedDataSlot(TiketKey)) as string;
                LogonInfo t = this.Decrypt(tiket);
                LogonInfo logonInfo = this.LogonInfoDao.FindByToken(t.Token);
                if (logonInfo != null)
                {
                    return logonInfo.User;
                }

                return null;
            }
        }

        [Transaction(ReadOnly=false)]
        public LogonInfo Logon(LogonInfo logonInfo)
        {
            logonInfo.User = this.UserDao.FindByUserName(logonInfo.UserName);
            if (logonInfo.User == null)
            {
                return null;
            }
            DateTime now = DateTime.Now;
            logonInfo.LogonTime = now;
            logonInfo.RefreshTime = now;
            logonInfo.ExpireTime = now.AddDays(2);
            logonInfo.IsOnline = true;

            this.LogonInfoDao.Save(logonInfo);

            return this.LogonInfoDao.FindById(logonInfo.Id);
        }

        [Transaction(ReadOnly = false)]
        public void Logoff(LogonInfo logonInfo)
        {
            logonInfo.RefreshTime = DateTime.Now;
            logonInfo.IsOnline = false;
            this.LogonInfoDao.SaveOrUpdate(logonInfo);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="logonInfo"></param>
        /// <returns></returns>
        public string Encrypt(LogonInfo logonInfo)
        {

            return "";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="tiket"></param>
        /// <returns></returns>
        private LogonInfo Decrypt(string tiket)
        {
            long id = Convert.ToInt64(tiket.Substring(0, 20));
            SecretKey secretKey = this.SecretKeyDao.FindById(id);
            return new LogonInfo() { };
        }
    }
}
